package face.pay.callback.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.common.cache.Cache;
import face.pay.cache.LocalCache;
import face.pay.callback.ISendBackMessageService;
import face.pay.callback.entity.OrderMessage;
import face.pay.dao.OemConfigInfoDao;
import face.pay.dao.OemProfitConfigInfoDao;
import face.pay.dao.OrderInfoDao;
import face.pay.entity.OemConfigInfo;
import face.pay.entity.OrderInfo;
import face.pay.server.IOemProfitConfigServer;
import face.pay.util.HttpClientUtil;
import face.pay.util.bean.JavaBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
/**
 * 针对 oem类型为OPEN 的订单
 * 支付成功后需要调用 oem 回调接口
 */
public class SendBackMessageServiceImpl implements ISendBackMessageService {

  @Autowired
  OemProfitConfigInfoDao oemProfitConfigInfoDao;

  @Autowired
  OrderInfoDao orderInfoDao;
  @Autowired
  IOemProfitConfigServer iOemProfitConfigServer;
  private Cache cache = LocalCache.cache;

  @Autowired
  private OemConfigInfoDao oemConfigInfoDao;


  @Async
  @Transactional(rollbackFor = Exception.class)
  public void callBack(String orderStr) throws  Exception{

    OrderInfo order = JSON.parseObject(orderStr,OrderInfo.class);

    Long orderId = order.getId();

    OrderInfo orderInfo  = this.orderInfoDao.getById(orderId);

    Integer status = orderInfo.getStatus();

    Integer callBackStatus = orderInfo.getCallBackStatus();

    Integer profitSign= orderInfo.getProfitSign();

    log.info("订单状态:"+status);
    log.info("订单回调状态:"+callBackStatus);
    log.info("订单profitSign:"+profitSign);

    if(new Integer(1).equals(status) && new Integer(0).equals(callBackStatus) && new Integer(0).equals(profitSign) ){


      Integer oemId = orderInfo.getOemId();

      OemConfigInfo oemConfigInfo = this.getOemConfig(oemId);

      String orderCallBackUrl = oemConfigInfo.getOrderCallBackUrl();

      String faceKey = oemConfigInfo.getFaceKey();

      log.info("orderCallBackUrl :"+orderCallBackUrl);
      log.info("faceKey "+faceKey);

      OrderMessage orderMessage =  new OrderMessage();
      BeanUtils.copyProperties(orderInfo,orderMessage);

      Map<String,String > data = JavaBeanUtils.toMap(orderMessage);

      String sign = WXPayUtil.generateSignature(data,faceKey);

      Map<String,Object> param = new HashMap<>();

      param.put("data", data);
      param.put("oemId",oemId);
      param.put("messageType", "ORDER_SUCCESS_CALLBACK");
      param.put("sign", sign);

      String json = JSON.toJSONString(param);
      log.info("发起回调 参数："+json);
      try {
        String returnMessage =  HttpClientUtil.doPostJson(orderCallBackUrl,json);
        log.info("回调 返回："+returnMessage);

        JSONObject jsonObject = JSONObject.parseObject(returnMessage);

        String returnStatus = jsonObject.getString("status");

        if("SUCCESS".equals(returnStatus)){
          orderInfo.setCallBackStatus(1);
        }

        }catch (Exception e){
          log.error("发送回调失败",e);
          orderInfo.setCallBackStatus(-1);
        }

        orderInfo.setProfitSign(-1);
        this.orderInfoDao.updatePayInfo(orderInfo);
    }else {
        log.info("订单已处理");
    }

  }


  private OemConfigInfo getOemConfig(Integer oemId){

    log.info("获取OEM配置信息");
    String key = "OEM_CONFIG_"+oemId;
    OemConfigInfo oemConfigInfo =   ( OemConfigInfo)cache.getIfPresent(key);
    String callBackUrl = null;

    if(oemConfigInfo==null){
       oemConfigInfo = this.oemConfigInfoDao.getByOemId(oemId);
      if(StringUtils.isNotBlank(oemConfigInfo.getOrderCallBackUrl())){
        cache.put(key,oemConfigInfo);

      }
    }
    return  oemConfigInfo;
  }

}
